package com.kelly.xml;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class SearchXml {

	
	public static NodeList searchNodeListByXpath(String xmlStr,String xPathExpression){
		try {
			 Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlStr)));
			 XPathFactory factory = XPathFactory.newInstance();
			 XPath xPath = factory.newXPath();
			 
			 XPathExpression expr = xPath.compile(xPathExpression);
			 return (NodeList)expr.evaluate(document, XPathConstants.NODESET);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<String> getValueByXPath(String xmlStr,String xPathExpression){
		NodeList nodeList = searchNodeListByXpath(xmlStr, xPathExpression);
		if(nodeList == null || nodeList.getLength()==0){
			return null;
		}
		List<String> result = new ArrayList<>(nodeList.getLength());
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			result.add(node.getTextContent());
		}
		return result;
	}
}
